<template>
  <div class="user-page">
    <div class="container">
      <!-- 用户信息卡片 -->
      <div class="user-card card">
        <div class="user-info">
          <div class="user-avatar">
            <el-avatar :size="80" :src="userInfo.avatar"></el-avatar>
          </div>
          <div class="user-detail">
            <h2 class="user-name">{{ userInfo.nickname }}</h2>
            <p class="user-bio">{{ userInfo.bio }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-count">{{ userInfo.articleCount }}</div>
                <div class="stat-label">文章</div>
              </div>
              <div class="stat-item">
                <div class="stat-count">{{ userInfo.followingCount }}</div>
                <div class="stat-label">关注</div>
              </div>
              <div class="stat-item">
                <div class="stat-count">{{ userInfo.followerCount }}</div>
                <div class="stat-label">粉丝</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 内容区域 -->
      <div class="content-section">
        <el-tabs v-model="activeTab" class="user-tabs">
          <el-tab-pane label="文章" name="articles">
            <!-- 文章列表 -->
            <div class="article-list" v-if="articles.length > 0">
              <div 
                v-for="article in articles" 
                :key="article.id" 
                class="article-item card" 
                @click="goToDetail(article.id)">
                <div class="article-main">
                  <div class="article-info">
                    <h3 class="article-title">{{ article.title }}</h3>
                    <p class="article-summary">{{ article.summary }}</p>
                    <div class="article-meta">
                      <span class="category-tag">{{ getCategoryName(article.categoryId) }}</span>
                      <span><el-icon><Timer /></el-icon> {{ article.publishTime }}</span>
                      <span><el-icon><View /></el-icon> {{ article.views }}</span>
                      <span><el-icon><ChatDotRound /></el-icon> {{ article.comments }}</span>
                      <span><el-icon><Star /></el-icon> {{ article.likes }}</span>
                    </div>
                  </div>
                  <div class="article-cover" v-if="article.coverUrl">
                    <img :src="article.coverUrl" :alt="article.title">
                  </div>
                </div>
                <div class="article-actions" @click.stop>
                  <el-button 
                :type="article.status === 1 ? 'success' : article.status === 2 ? 'warning' : 'danger'" 
                size="small"
                 v-if="user_id == userInfo.id"
              >
                <el-icon>
                  <Check v-if="article.status === 1" />
                  <Close v-else-if="article.status === 2" />  
                </el-icon>
                {{ 
                  article.status === 1 ? '审核通过' : 
                  article.status === 2 ? '审核中' : 
                  '审核不通过' 
                }}
              </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteArticle(article.id)"  v-if="user_id == userInfo.id">
                    <el-icon><Delete /></el-icon> 删除文章
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 无内容 -->
            <div class="no-content" v-else>
              <el-empty description="暂无发布的文章"></el-empty>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="点赞" name="likes">
            <!-- 点赞列表 -->
            <div class="article-list" v-if="likedArticles.length > 0">
              <div 
                v-for="article in likedArticles" 
                :key="article.articleId" 
                class="article-item card" 
                @click="goToDetail(article.articleId)">
                <div class="article-main">
                  <div class="article-info">
                    <h3 class="article-title">{{ article.title }}</h3>
                    <p class="article-summary">{{ article.summary }}</p>
                    <div class="article-meta">
                      <span class="author">
                        <el-avatar :size="20" :src="article.avatar || userAvatar"></el-avatar>
                        {{ article.nickname }}
                      </span>
                      <span><el-icon><Timer /></el-icon> {{ article.time }}</span>
                      <span><el-icon><View /></el-icon> {{ article.views }}</span>
                      <span><el-icon><ChatDotRound /></el-icon> {{ article.comments }}</span>
                      <span><el-icon><Star /></el-icon> {{ article.likes }}</span>
                    </div>
                  </div>
                  <div class="article-cover" v-if="article.img && isValidImage(article.img)">
                    <img :src="article.img" :alt="article.title" @error="handleImageError">
                  </div>
                </div>
                <div class="article-actions" @click.stop>
                  <el-button type="primary" size="small" @click="handleUnlike(article.articleId)"  v-if="user_id == userInfo.id">
                    <el-icon><Star /></el-icon> 取消点赞
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 无内容 -->
            <div class="no-content" v-else>
              <el-empty description="暂无点赞的文章"></el-empty>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="关注" name="followings">
            <!-- 关注的用户列表 -->
            <div class="user-list" v-if="followings.length > 0">
              <div v-for="user in followings" :key="user.id" class="user-item card">
                <div class="user-item-info">
                  <el-avatar :size="50" :src="user.avatar" @click="goToUser(user.followingId)"></el-avatar>
                  <div class="user-item-detail">
                    <h3 class="user-item-name" @click="goToUser(user.followingId)">{{ user.nickname }}</h3>
                    <p class="user-item-bio">{{ user.time }}</p>
                  </div>
                </div>
                <div class="user-actions">
                  <el-button type="primary" size="small" @click="handleUnfollow(user.id)" v-if="user_id == userInfo.id">
                    <el-icon><Close /></el-icon> 取消关注
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 无内容 -->
            <div class="no-content" v-else>
              <el-empty description="暂无关注的用户"></el-empty>
            </div>
          </el-tab-pane>
        </el-tabs>
        
        <!-- 分页 -->
        <div class="pagination-section" v-if="getTotalItems > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="getTotalItems"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Timer, View, ChatDotRound, Star, Delete, Close } from '@element-plus/icons-vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

// 数据

const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
let userId = route.params.id
const user_id = localStorage.getItem('id')
// const username = localStorage.getItem('username')
const activeTab = ref('articles')
const currentPage = ref(1)
const pageSize = ref(10)
const categories = ref([
  { id: 1, name: '科技' },
  { id: 2, name: '娱乐' },
  { id: 3, name: '体育' },
  { id: 4, name: '国际' },
  { id: 5, name: '财经' },
  { id: 6, name: '教育' },
  { id: 7, name: '文化' },
  { id: 8, name: '动漫' }
])
const userInfo = ref({
  id: 0,
  username: '',
  avatar: '',
  bio: '',
  nickname: '',
  articleCount: 0,
  followingCount: 0,
  followerCount: 0,
  likeCount: 0
})
const articles = ref([])
const likedArticles = ref([])
const followings = ref([])

//检查图片是否有效
const isValidImage = (url) => {
  return url && url.trim() !== ''
}
const getTotalItems = computed(() => {
  switch (activeTab.value) {
    case 'articles':
      return userInfo.value.articleCount
    case 'likes':
      return likedArticles.value.length
    case 'followings':
      return followings.value.length
    default:
      return 0
  }
})

// 监听器
watch(() => route.params.id, (newVal) => {
  userId = parseInt(newVal)
  fetchUserData()
  fetchArticles()
  fetchLikedArticles()
  fetchFollowings()
})

watch(activeTab, () => {
  currentPage.value = 1
  loadTabData()
  fetchFollowings()
  
})

// 生命周期钩子
onMounted(() => {
  fetchUserData()
  fetchArticles()

})

// 方法
const fetchUserData = async () => {
  try {
    const res = await request.get(`/user/personal/${userId}`)
    if (res.data.code === '200') {
      userInfo.value = {
        id: res.data.data.id,
        username: res.data.data.username,
        nickname: res.data.data.nickName,
        avatar: res.data.data.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        bio: res.data.data.bio || '这个人很懒，什么都没留下',
        articleCount: res.data.data.articlesNum || 0,
        followingCount: res.data.data.followNum || 0,
        followerCount: res.data.data.likesNum || 0,
        likeCount: res.data.data.likeCount || 0
      }
    }
    console.log('id',userInfo.value.id);
    
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}


const loadTabData = () => {
  switch (activeTab.value) {
    case 'articles':
      fetchArticles()
      break
    case 'likes':
      fetchLikedArticles()
      break
    case 'followings':
      fetchFollowings()
      break
  }
}

//文章
const fetchArticles = async () => {
  try {
    const res = await request.get('/articles/personal/page', {
      params: {
        authorId: userId,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    if (res.data.code === '200') {
      articles.value = res.data.data.records || []
      userInfo.value.articleCount = res.data.data.total || 0
    }
  } catch (error) {
    console.error('获取用户文章失败:', error)
    ElMessage.error('获取文章列表失败')
  }
}

//点赞列表
const fetchLikedArticles = async () => {
  try {
    const res = await request.get('/likes/page', {
      params: {
        userId: userId,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    if (res.data.code === '200') {
      likedArticles.value = res.data.data.records || []
    }
  } catch (error) {
    console.error('获取点赞文章失败:', error)
    ElMessage.error('获取点赞文章列表失败')
  }
}

//关注列表
const fetchFollowings = async () => {
  try {
    const res = await request.get('/follow/page', {
      params: {
        followingId: userId,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    if (res.data.code === '200') {
      followings.value = res.data.data.records || []
      userInfo.value.followingCount = res.data.data.total || 0
    }
   
    
  } catch (error) {
    console.error('获取关注列表失败:', error)
    ElMessage.error('获取关注列表失败')
  }
}

const getCategoryName = (id) => {
  const category = categories.value.find(item => item.id === id)
  return category ? category.name : '未分类'
}

const goToDetail = (id) => {
  router.push(`/detail/${id}`)
}

const goToUser = (id) => {
  if (id !== userId) {
    router.push(`/user/${id}`)
  }
}

const handlePageChange = async (page) => {
  currentPage.value = page
  await loadTabData()
  window.scrollTo(0, 0)
}

const handleSizeChange = async (size) => {
  pageSize.value = size
  currentPage.value = 1
  await loadTabData()
  window.scrollTo(0, 0)
}

// 删除文章
const handleDeleteArticle = async (articleId) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete(`/articles/${articleId}`)
    if (res.data.code === '200') {
      ElMessage.success('删除成功')
      // 重新加载文章列表
      fetchArticles()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 取消点赞
const handleUnlike = async (articleId) => {
  try {
    const res = await request.post('/articles/unLike', {
      articleId: articleId,
      userId: userId
    })
    
    if (res.data.code === '200') {
      ElMessage.success('已取消点赞')
      // 重新加载点赞列表
      fetchLikedArticles()
    } else {
      ElMessage.error(res.data.msg || '取消点赞失败')
    }
  } catch (error) {
    console.error('取消点赞失败:', error)
    ElMessage.error('取消点赞失败，请稍后重试')
  }
}

// 取消关注
const handleUnfollow = async (id) => {
  try {
    const res = await request.delete(`/follow/${id}`)
    if (res.data.code === '200') {
      ElMessage.success('已取消关注')
      // 重新加载关注列表
      fetchFollowings()
    } else {
      ElMessage.error(res.data.msg || '取消关注失败')
    }
  } catch (error) {
    console.error('取消关注失败:', error)
    ElMessage.error('取消关注失败，请稍后重试')
  }
}
</script>

<style scoped>
.user-page {
  padding: 20px 0 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.user-card {
  margin-bottom: 20px;
  padding: 25px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 20px;
}

.user-detail {
  flex: 1;
}

.user-name {
  font-size: 24px;
  margin-bottom: 5px;
}

.user-bio {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.user-stats {
  display: flex;
}

.stat-item {
  margin-right: 30px;
  text-align: center;
}

.stat-count {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #999;
}

.content-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  padding: 20px;
}

.user-tabs {
  margin-bottom: 20px;
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.article-item {
  padding: 15px;
  cursor: pointer;
}

.article-main {
  display: flex;
  gap: 20px;
}

.article-info {
  flex: 1;
}

.article-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.article-summary {
  color: #666;
  margin-bottom: 10px;
  line-height: 1.6;
}

.article-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 13px;
  color: #999;
}

.article-meta > span {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 5px;
}

.article-meta .el-icon {
  margin-right: 5px;
}

.category-tag {
  background-color: #f4f4f5;
  color: #909399;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.author {
  display: flex;
  align-items: center;
  gap: 5px;
}

.article-cover {
  width: 180px;
  height: 120px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.article-item:hover .article-cover img {
  transform: scale(1.05);
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-item {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-item-info {
  display: flex;
  align-items: center;
}

.user-item-detail {
  margin-left: 15px;
}

.user-item-name {
  font-size: 16px;
  margin-bottom: 5px;
  cursor: pointer;
}

.user-item-name:hover {
  color: #409eff;
}

.user-item-bio {
  color: #666;
  font-size: 14px;
}

.no-content {
  padding: 40px 0;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.article-actions,
.user-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
  border-top: 1px solid #eee;
  margin-top: 10px;
}

.article-actions .el-button,
.user-actions .el-button {
  margin-left: 10px;
}

@media screen and (max-width: 768px) {
  .user-info {
    flex-direction: column;
    text-align: center;
  }
  
  .user-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .article-main {
    flex-direction: column;
  }
  
  .article-cover {
    width: 100%;
    height: 180px;
    margin-top: 10px;
  }
  
  .article-actions,
  .user-actions {
    justify-content: center;
  }
}
</style> 